import { NonDialogPickableCommandForm } from '@app-cad/common/components/command-form/pickable';
import { useCommand } from '@app-cad/common/hooks/useCommand';
import { nmAppLog } from '@app-nextmesh/common/utils';
import { documentV2 } from '@app-nextmesh/domain';
import { RJSFSchema, UiSchema } from '@rjsf/utils';
import { useEffect, useState } from 'react';
import { Vector3Tuple } from 'three-legacy';

type InitData = { [key: string]: any };
interface Props {
  onClose: () => void;
  formatParam: (formData: InitData) => {
    source?: string[] | Vector3Tuple[] | string;
    target?: string[];
    relyOn?: string[];
    mode?: string;
    ptType?: number;
    param?: number[];
    isEmbeded?: boolean[];
  };
  formParams: {
    extraUiSchema?: { [key in string]: UiSchema };
    schemaParams?: RJSFSchema;
  };
  pointInfo?: { [key: string]: any };
  wsApi?: string;
  callback?: (returnInfo?: any, formData?) => void;
  submitText?: string;
  cmdCommand?: string;
  onChange?: (formData: InitData) => void;
  onFocus?: (v) => void;
}
let param = null;
export function MsComponent({
  onClose,
  formatParam,
  formParams,
  pointInfo,
  callback,
  wsApi = 'intersectPoint',
  submitText = '确定',
  cmdCommand = 'topo',
  onChange,
  onFocus,
}: Props) {
  const [formData, setFormData] = useState({ pointType: 0 });
  useEffect(() => {
    setFormData((state) => {
      return {
        ...state,
        ...pointInfo,
      };
    });
  }, [pointInfo]);
  const execute = async (preview = false) => {
    if (param) {
      let res = null;
      try {
        res = await documentV2[wsApi](param, preview);
      } catch (e) {
        //
      }
      param = null;
      setFormData({ pointType: 0 });
      callback && callback(res);
    }
  };
  const checkAndFinishDraw = async () => {
    nmAppLog('execute');
    execute();
  };
  const isFormDataValid = () => {
    param = formatParam(formData);
    return param ? true : false;
  };
  // const preview = async () => {
  //   await execute(true);
  // };
  useCommand('cmd-mesh-' + (cmdCommand || wsApi), {
    onClose,
    finishDraw: checkAndFinishDraw,
  });
  return (
    <NonDialogPickableCommandForm
      // onPreview={preview}
      className='-mt-3'
      onCancel={onClose}
      schema={formParams.schemaParams}
      formData={formData}
      onChange={(v) => {
        setFormData((state) => ({ ...state, ...v }));
        onChange && onChange(v);
      }}
      onFocus={(v) => {
        onFocus && onFocus(v);
      }}
      extraUiSchema={formParams.extraUiSchema}
      submitText={submitText}
      onSubmit={checkAndFinishDraw}
      isFormDataValid={isFormDataValid()}
    />
  );
}
